#!/usr/bin/python
import sys
import urllib2
import re
import json
import string
from xml.etree import ElementTree as ET
from filmset import MyVideo
def fromFile():
    f = open('qy.m3u')
    line = f.readline()
    f.close()
    if len(line)>6:
        return line[5:].strip()
    else :
        return ''
def nextFile():
    f = open('qy.m3u')
    f.readline()
    line = f.readline()
    f.close()
    if len(line)>7:
        return line[6:].strip()
    else :
        return ''
def getXmlUrl(myVideo):
    req = urllib2.Request(myVideo.url,"",myVideo.headers);
    data = urllib2.urlopen(req,timeout=10).read();
    myrule = '[\"]*data-player-videoid[\" ]*=[ ]*[\"]([^\"]+)[\"]';
    videoIds=re.findall(myrule,data,re.I)
    if len(videoIds):
        return 'http://cache.video.qiyi.com/v/'+videoIds[0] 
    else:
        return ''
def getQyTime():
    req = urllib2.Request('http://data.video.qiyi.com/t.hml',"",myVideo.headers);
    data = urllib2.urlopen(req,timeout=10).read(); 
    res = json.loads(data)
    return string.atoi(res['t'],10) ^ 1717152535
def getPlay(url,mtime):
    newurl = url[:url.rfind('.')] + '.hml?v='+str(mtime)
    req = urllib2.Request(newurl,"",myVideo.headers)
    data = urllib2.urlopen(req,timeout=10).read()
    res = json.loads(data)
    return res['l']
def xmlDone(myVideo,url):
    req = urllib2.Request(url,"",myVideo.headers);
    xmlcontent = urllib2.urlopen(req,timeout=20).read();
    root = ET.fromstring(xmlcontent);
    videoE = root.find('video');
    nUrl = videoE.find('nextVideoUrl').text;
    if not nUrl is None:
        myVideo.setNUrl(nUrl);
    files = videoE.find('fileUrl');
    for item in files.getchildren():
        myVideo.addfile(item.text);
    return myVideo;
# Script starts from here
if len(sys.argv) < 2:
    print 'No action specified.'
elif sys.argv[1].startswith('--'):
   option = sys.argv[1][2:]
   # fetch sys.argv[1] but without the first two characters
   if option == 'm3u' or option == 'rmvb' or option == 'update' or option == 'next':
      if option == 'update':
          myVideo = MyVideo(fromFile())
      elif option == 'next':
          myVideo = MyVideo(nextFile())
      else:
          myVideo = MyVideo(sys.argv[2])
      xmlurl = getXmlUrl(myVideo)
      if len(xmlurl)>0:
         xmlDone(myVideo,xmlurl)
         mtime = getQyTime()
         for item in myVideo.files:
             play = getPlay(item,mtime)
             myVideo.addplayer(play)
         if option == 'rmvb':
             myVideo.download()
         else:
             myVideo.saveFile('qy.m3u')
   elif option == 'help':
      print '''This Application Version is 0.2
Options include:
--m3u <url> : make file from url
--update    : self update m3u file
--next      : self update next m3u file
--rmvb <url>: download files from url
--help      : Display this help'''
   else:
       print 'Unknown option.'
sys.exit();
